from window_login import LoginWindow
from request_protocol import RequestProtocol
from client_socket import ClientSocket
from threading import Thread
from config import *
from tkinter.messagebox import showinfo
from window_chat import WindowChat
import sys


class Client(object):
    def __init__(self):
        self.window = LoginWindow()
        self.window.on_reset_button(self.clear_inputs)
        self.window.on_login_button(self.send_login_data)

        self.conn = ClientSocket()

        self.username = None
        self.is_runing = True

        self.response_handle_function = {}
        # self.response_handle_function[RESPONSE_LOGIN_RESULT] = self.response_login_handle
        # self.response_handle_function[RESPONSE_CHAT] = self.response_chat_handle
        self.register(RESPONSE_LOGIN_RESULT, self.response_login_handle)
        self.register(RESPONSE_CHAT, self.response_chat_handle)

        self.window_chat = WindowChat()
        self.window_chat.withdraw()
        self.window.on_window_close(self.exit)
        self.window_chat.on_window_close(self.exit)

        self.window_chat.on_send_click(self.send_chat_data)

    def register(self, request_id, handle):
        self.response_handle_function[request_id] = handle
    def start_up(self):
        self.conn.connect()
        Thread(target=self.response_handle).start()

        self.window.mainloop()

    def clear_inputs(self):
        self.window.clear_username()
        self.window.clear_password()

    def send_login_data(self):
        username = self.window.get_username()
        password = self.window.get_password()

        text = RequestProtocol.request_login_result(username, password)

        self.conn.send_data(text)

        # result = self.conn.recv_data()
        # print(result)

    def response_handle(self):

        while self.is_runing:
            recv_data = self.conn.recv_data()
            print(recv_data)

            response_data = self.parse_response_data(recv_data)

            # if response_data['response_id'] == RESPONSE_LOGIN_RESULT:
            #     self.response_login_handle(response_data)
            # elif response_data['response_id'] == RESPONSE_CHAT:
            #     self.response_chat_handle(response_data)

            handle_function = self.response_handle_function[response_data['response_id']]

            if handle_function:
                handle_function(response_data)


    @staticmethod
    def parse_response_data(recv_data):
        response_data_list = recv_data.split(DELIMITER)

        response_data = {}

        response_data['response_id'] = response_data_list[0]

        if response_data['response_id'] == RESPONSE_LOGIN_RESULT:
            response_data['result'] = response_data_list[1]
            response_data['nickname'] = response_data_list[2]
            response_data['username'] = response_data_list[3]
        elif response_data['response_id'] == RESPONSE_CHAT:
            response_data['nickname'] = response_data_list[1]
            response_data['message'] = response_data_list[2]

        return response_data

    def response_login_handle(self, response_data):

        print('接收到登录信息', response_data)

        result = response_data['result']

        if result == '0':
            showinfo('提示','登陆失败！账号或密码错误！')
            #print('登陆失败')
            return

        showinfo('提示', '登陆成功')
        nick_name = response_data[('nickname')]

        self.username = response_data.get('username')

        # print(nick_name, username, '登陆成功')

        self.window_chat.set_title(nick_name)
        self.window_chat.update()
        self.window_chat.deiconify()
        self.window.withdraw()





    def response_chat_handle(self, response_data):
        print('接收到聊天信息', response_data)

        sender = response_data['nickname']
        message = response_data['message']
        self.window_chat.append_message(sender, message)

    def send_chat_data(self):
        message = self.window_chat.get_input()
        self.window_chat.clear_input()

        request_text = RequestProtocol.request_chat(self.username, message)
        self.conn.send_data(request_text)

        self.window_chat.append_message('我', request_text)

    def exit(self):
        self.is_runing = False
        self.conn.close()
        sys.exit(0)


if __name__ == '__main__':
    client = Client()
    client.start_up()